import { imgLoad } from './utils';

export default class Lazyimg {
  constructor({ el, src, options, imgRender }) {
    //img el
    this.el = el;
    //正常src/loading src/error src
    this.src = src;
    //用户配置
    this.options = options;
    //渲染真实图片地址/error地址/loading地址
    this.imgRender = imgRender;
    //flag 图片是否有加载
    this.loaded = false;
    //flag
    this.state = {
      loading: false,
      error: false,
    };
  }

  checkIsVisible() {
    //查找图片到顶部的距离
    const { top } = this.el.getBoundingClientRect();

    //小于窗口高度 x 用户设置的倍数(默认1.3)
    const bool = top < window.innerHeight * (this.options.preload || 1.3);

    // console.log(bool); true / false;

    //当一张图片触顶时返回true
    //当所有图片触底时一直返回true
    return bool;
  }

  loadImg() {
    //显示loading图
    this.imgRender(this, 'loading');

    imgLoad(this.src).then(
      () => {
        //resolve
        this.state.loading = true;

        //显示常规图片
        this.imgRender(this, 'ok');
        this.loaded = true;
      },
      () => {
        //reject
        this.state.error = true;

        //显示error图
        this.imgRender(this, 'error');
        this.loaded = true;
      }
    );
  }
}
